package main 
{
	import assists.URI;
	import assists.caches.CacheFile;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.System;
	import flash.utils.ByteArray;
	
	/**
	 * ...
	 * @author clouree
	 */
	public class XMLLoaderBase  extends SuperSubBase
	{
		private var _xmlLoader:URLLoader;
		private var _urlRequest:URLRequest;
		private var _loadCompleteFunc:Function;
		private var _progressFunc:Function;
		private var _isLoaded:Boolean;
		private var _data:Object = {};
		protected var _xmlManager:XMLLoaderManager;
		private var _xml:XML;
		
		private var _cacheFile:CacheFile;
		private var namePath:String;
		
		public function XMLLoaderBase()
		{
			_xmlLoader = new URLLoader();
			
			_cacheFile = new CacheFile;
		}
		
		public function get uri():URI
		{
			return _xmlManager.uri;
		}
		
		public function loadXml(url:String, completeFunc:Function,progressFun:Function = null):void
		{
			namePath = url;
			
			if(_isLoaded)
			{
				_loadCompleteFunc(_xml);
			}else
			{
				_loadCompleteFunc = completeFunc;
				_progressFunc = progressFun;
				_urlRequest = new URLRequest(url);
				_xmlLoader.addEventListener(Event.COMPLETE, loadComplete);
				_xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, loadError);
				_xmlLoader.addEventListener(ProgressEvent.PROGRESS, progressFunc);
				_xmlLoader.load(_urlRequest);
			}
		}
		
		private function progressFunc(e:ProgressEvent):void 
		{
			trace("load" + e.bytesLoaded + "/" + e.bytesTotal);
			if (_progressFunc != null)
			{
				_progressFunc();
			}
		}
		
		private function loadError(e:IOErrorEvent):void 
		{
			trace("loadError" + e.errorID);
		}
		
		private function loadComplete(e:Event):void 
		{
			_isLoaded = true;
			_xml = new XML(e.target.data);
			
			if(namePath.indexOf("clientResource") != -1){
				var er:ByteArray = new ByteArray;
				er.writeUTFBytes(_xml .toString());
				
				_cacheFile.saveXML(er,namePath.split("assets/")[1]);
			}
			
			_loadCompleteFunc(_xml);
			//			System.disposeXML(xml);
			changeToData(_xml);
		}
		
		private function changeToData(value:XML):void
		{
		}
		
		private function clearEvent():void
		{
			_xmlLoader.removeEventListener(Event.COMPLETE, loadComplete);
			_xmlLoader.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
			_xmlLoader.removeEventListener(ProgressEvent.PROGRESS, progressFunc);
		}
		
		override public function initComponents(value:SuperBase):void
		{
			if (!value)
			{
				trace("传入组件为空");
				return;
			}
			_xmlManager = value as XMLLoaderManager;
			
		}
		
	}
}